package ltd.dujiabao.activemq.queue;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import javax.jms.*;
import java.io.IOException;

/**
 * @author : DuJiabao
 * @Project : active-mq
 * @Time : 2021/5/4 18:44
 * @Desc :
 */
public class QueueProducer {
  private static final String ACTIVEMQ_URL = "tcp://192.168.233.134:61616";  // 服务器端口号，地址
  //private static final String ACTIVEMQ_URL = "tcp://127.0.0.1:61616";  // 服务器端口号，地址
  //private static final String ACTIVEMQ_URL = "nio://192.168.233.134:61618";  // 服务器端口号，地址
  private static final String DESTINATION_NAME = "queue01";  // 目的地名称
  private ActiveMQConnectionFactory activeMQConnectionFactory;
  private Connection connection = null;
  private Session session = null;
  private MessageProducer producer = null;

  @Before
  public void before() throws JMSException {
    activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
    connection = activeMQConnectionFactory.createConnection();
    connection.start();
    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);// 不使用事务，使用自动签收
  }

  @Test
  public void test1() throws JMSException {
    // 通过session把角色都创建出来
    Queue queue = session.createQueue(DESTINATION_NAME);  // 创建一个消息队列出来，也就是目的地
    producer = session.createProducer(queue);  // 把目的地放进生产者里面
    // 发送消息
    for (int i = 0; i < 10; i++) {
      TextMessage message = session.createTextMessage("message:" + i);// 创建一个要发送的消息对象，该对象存储的是字符串
      producer.send(message);// 生产者负责将消息对象发送出去
    }
    System.out.println("发送消息完毕");
  }

  @After
  public void after() throws JMSException {
    // 关闭资源
    producer.close();
    session.close();
    connection.close();
    System.out.println("资源关闭完毕");
  }
}
